home *** CD-ROM | disk | FTP | other *** search
/ C & C++ Multimedia Cyber Classroom / C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso / src / fig07_04.jar / Ch07 / Fig07_04 / Date1.cpp next >
C/C++ Source or Header  |  1997-10-20  |  2KB  |  60 lines

  1. // Fig. 7.4: date.cpp
  2. // Member function definitions for Date class.
  3. #include <iostream.h>
  4. #include "date1.h"
  5.  
  6. // Constructor: Confirm proper value for month;
  7. // call utility function checkDay to confirm proper
  8. // value for day.
  9. Date::Date( int mn, int dy, int yr )
  10. {
  11.    if ( mn > 0 && mn <= 12 )       // validate the month
  12.       month = mn;
  13.    else {
  14.       month = 1;
  15.       cout << "Month " << mn << " invalid. Set to month 1.\n";
  16.    }
  17.  
  18.    year = yr;                      // should validate yr
  19.    day = checkDay( dy );           // validate the day
  20.  
  21.    cout << "Date object constructor for date ";
  22.    print();         // interesting: a print with no arguments
  23.    cout << endl;
  24. }
  25.  
  26. // Print Date object in form  month/day/year
  27. void Date::print() const
  28.    { cout << month << '/' << day << '/' << year; }
  29.  
  30. // Destructor: provided to confirm destruction order
  31. Date::~Date()
  32.    cout << "Date object destructor for date ";
  33.    print();
  34.    cout << endl;
  35. }
  36.  
  37. // Utility function to confirm proper day value
  38. // based on month and year.
  39. // Is the year 2000 a leap year?
  40. int Date::checkDay( int testDay )
  41. {
  42.    static const int daysPerMonth[ 13 ] = 
  43.       {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  44.  
  45.    if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
  46.       return testDay;
  47.  
  48.    if ( month == 2 &&      // February: Check for leap year
  49.         testDay == 29 &&
  50.         ( year % 400 == 0 ||                      // year 2000?
  51.          ( year % 4 == 0 && year % 100 != 0 ) ) ) // year 2000?
  52.       return testDay;
  53.  
  54.    cout << "Day " << testDay << " invalid. Set to day 1.\n";
  55.  
  56.    return 1;  // leave object in consistent state if bad value
  57. }
  58.  
  59.